<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Customer Portal</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f4f4f4;
        }
        .container {
            width: 300px;
            background: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
        }
        .hidden {
            display: none;
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
        }
        .form-group input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
        }
        .form-group button {
            width: 100%;
            padding: 10px;
            background-color: #007bff;
            border: none;
            color: #fff;
            cursor: pointer;
            border-radius: 4px;
        }
        .form-group button:hover {
            background-color: #0056b3;
        }
        .nav-links {
            display: flex;
            justify-content: space-between;
        }
        .nav-links button {
            background: none;
            border: none;
            color: #007bff;
            cursor: pointer;
        }
        .popup {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            border-radius: 8px;
            z-index: 1000;
        }
        .popup table {
            width: 100%;
            border-collapse: collapse;
        }
        .popup table, .popup th, .popup td {
            border: 1px solid #ddd;
        }
        .popup th, .popup td {
            padding: 8px;
            text-align: left;
        }
        .popup th {
            background-color: #f4f4f4;
        }
        .popup button {
            margin-top: 10px;
        }
        .overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 999;
        }

        #payButton {
            margin-top: 10px;
            padding: 10px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        #payButton:disabled {
            background-color: #ccc;
        }

    </style>
</head>
<body>
<div class="container">
    <!-- Login Section -->
    <div id="loginSection">
        <h2>Customer LogIn</h2>
        <div class="form-group">
            <label for="loginUsername">Username</label>
            <input type="text" id="loginUsername" name="username">
        </div>
        <div class="form-group">
            <label for="loginPassword">Password</label>
            <input type="password" id="loginPassword" name="password">
        </div>
        <div class="form-group">
            <button onclick="loginCustomer()">Log In</button>
        </div>
        <div class="nav-links">
            <button onclick="showSection('registerSection')">Customer Register</button>
            <button onclick="showSection('forgetPasswordSection')">Forget Password</button>
        </div>
    </div>

    <!-- Register Section -->
    <div id="registerSection" class="hidden">
        <h2>Customer Register</h2>
        <div class="form-group">
            <label for="registerUsername">Username</label>
            <input type="text" id="registerUsername" name="username">
        </div>
        <div class="form-group">
            <label for="registerPassword">Password</label>
            <input type="password" id="registerPassword" name="password">
        </div>
        <div class="form-group">
            <label for="phoneNumber">Phone Number</label>
            <input type="text" id="phoneNumber" name="phoneNumber">
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" id="email" name="email">
        </div>
        <div class="form-group">
            <button onclick="registerCustomer()">Register</button>
        </div>
        <div class="nav-links">
            <button onclick="showSection('loginSection')">Customer LogIn</button>
            <button onclick="showSection('forgetPasswordSection')">Forget Password</button>
        </div>
    </div>

    <!-- Forget Password Section -->
    <div id="forgetPasswordSection" class="hidden">
        <h2>Forget Password</h2>
        <div class="form-group">
            <label for="forgetUsername">Username</label>
            <input type="text" id="forgetUsername" name="username">
        </div>
        <div class="form-group">
            <label for="forgetEmail">Email</label>
            <input type="email" id="forgetEmail" name="email">
        </div>
        <div class="form-group">
            <button onclick="resetPassword()">Reset Password</button>
        </div>
        <div class="nav-links">
            <button onclick="showSection('loginSection')">Customer LogIn</button>
            <button onclick="showSection('registerSection')">Customer Register</button>
        </div>
    </div>

    <!-- Update Password Section -->
    <div id="updatePasswordSection" class="hidden">
        <h2>Update Password</h2>
        <div class="form-group">
            <label for="currentPassword">Current Password</label>
            <input type="password" id="currentPassword">
        </div>
        <div class="form-group">
            <label for="newPassword">New Password</label>
            <input type="password" id="newPassword">
        </div>
        <div class="form-group">
            <button onclick="updatePassword()">Update Password</button>
        </div>
        <div class="nav-links">
            <button onclick="showSection('shoppingSection')">Shopping Options</button>
        </div>
    </div>

    <!-- Shopping Section -->
    <div id="shoppingSection" class="hidden">
        <h2>Shopping Options</h2>
        <button onclick="showProductList()">View Products</button>
        <button onclick="viewPurchaseHistory()">View Purchase History</button>
        <button onclick="viewCart()">View Cart</button>
        <button id="payButton">Pay</button>
        <div id="productPopup" class="popup hidden">
            <h2>Products</h2>
            <table id="productTable">
                <thead>
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Price</th>
                    <th>Quantity</th>
                    <th>Action</th>
                </tr>
                </thead>
                <tbody></tbody>
            </table>
            <button onclick="hideProductPopup()">Close</button>
        </div>
    </div>
</div>

<div id="cartPopup" class="popup hidden">
    <h2>Cart</h2>
    <table id="cartTable">
        <thead>
        <tr>
            <th>Product ID</th>
            <th>Quantity</th>
            <th>Action</th>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
    <button onclick="hideProductPopup()">Close</button>
</div>



<!-- Overlay for Popups -->
<div id="overlay" class="overlay hidden"></div>


<script>
    let customerId = 1;

    function showSection(sectionId) {
        document.getElementById('loginSection').classList.add('hidden');
        document.getElementById('registerSection').classList.add('hidden');
        document.getElementById('forgetPasswordSection').classList.add('hidden');
        document.getElementById('updatePasswordSection').classList.add('hidden');
        document.getElementById('shoppingSection').classList.add('hidden');
        document.getElementById(sectionId).classList.remove('hidden');
    }

    function loginCustomer() {
        const username = document.getElementById('loginUsername').value;
        const password = document.getElementById('loginPassword').value;
        fetch('http://127.0.0.1:8080/CustomerService/loginCustomer', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ username, password })
        }).then(response => response.json())
            .then(data => {
                customerId = data.id; // Assuming response contains customerId
                showSection('updatePasswordSection');
            }
        );
    }

    function registerCustomer() {
        const username = document.getElementById('registerUsername').value;
        const password = document.getElementById('registerPassword').value;
        const phoneNumber = document.getElementById('phoneNumber').value;
        const email = document.getElementById('email').value;
        fetch('http://127.0.0.1:8080/CustomerService/registerCustomer', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ username, password, phoneNumber, email })
        })
            .then(response => {
                if (response.ok) {
                    alert('Registration successful!');
                    showSection('loginSection');
                } else {
                    alert('Registration failed!');
                }
            })
            .catch(() => {
                alert('error,Registration failed!');
            });
    }


    function resetPassword() {
        const username = document.getElementById('forgetUsername').value;
        const email = document.getElementById('forgetEmail').value;

        fetch('http://127.0.0.1:8080/CustomerService/resetPassword', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ username, email })
        })
            .then(response => {
                if (response.ok) {
                    alert('Password reset link sent to your email.');
                    showSection('loginSection');
                } else {
                    return response.json().then(data => {
                        // Optionally handle the error message from the server
                        alert(data.message || 'Password reset failed!');
                    });
                }
            })
            .catch(() => {
                alert('Password reset failed!');
            });
    }


    function updatePassword() {
        const newPassword = document.getElementById('newPassword').value;
        const ID = String(customerId);

        fetch('http://127.0.0.1:8080/CustomerService/updatePassword?customerId=${customerId}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ ID, newPassword })
        })
            .then(response => {
                if (response.ok) {
                    alert('Password updated successfully!');
                } else {
                    return response.json().then(data => {
                        // Optionally handle the error message from the server
                        alert(data.message || 'Password update failed!');
                    });
                }
            })
            .catch(() => {
                alert('Password update failed!');
            });
    }


    function showProductList() {
        fetch('http://127.0.0.1:8080/AdminService/getAllProduct')
            .then(response => response.json())
            .then(products => {
                const tbody = document.querySelector('#productTable tbody');
                tbody.innerHTML = '';
                products.forEach(product => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                    <td>${product.id}</td>
                    <td>${product.name}</td>
                    <td><input type="number" value="1" min="1" id="quantity-${product.id}"></td>
                    <td><button onclick="addToCart(${product.id})">Add to Cart</button></td>
                `;
                    tbody.appendChild(tr);
                });

                const productPopup = document.getElementById('productPopup');
                const overlay = document.getElementById('overlay');
                if (productPopup && overlay) {
                    productPopup.classList.remove('hidden');
                    overlay.classList.remove('hidden');
                } else {
                    console.error('Element(s) not found.');
                }
            }).catch(() => {
            alert('Failed to load products.');
        });
    }


    function addToCart(productId) {
        const quantity = document.getElementById(`quantity-${productId}`).value;
        const ID = String(customerId);

        fetch('http://127.0.0.1:8080/CustomerService/addToCart', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({ ID, productId, quantity })
        })
            .then(response => {
                if (response.ok) {
                    alert('Product added to cart.');
                } else {
                    return response.json().then(data => {
                        // Optionally handle the error message from the server
                        alert(data.message || 'Failed to add product to cart.');
                    });
                }
            })
            .catch(() => {
                alert('Failed to add product to cart.');
            });
    }


    function viewPurchaseHistory() {
        const tbody = document.querySelector('#historyTable tbody');
        if (!tbody) {
            alert('Table body not found.');
            return;
        }

        fetch(`http://127.0.0.1:8080/CustomerService/getPurchaseHistory?customerId=${customerId}`)
            .then(response => response.json())
            .then(history => {
                tbody.innerHTML = '';
                history.forEach(record => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                    <td>${record.id}</td>
                    <td>${record.quantity}</td>
                `;
                    tbody.appendChild(tr);
                });
                document.getElementById('historyPopup').classList.remove('hidden');
                document.getElementById('overlay').classList.remove('hidden');
            })
            .catch(() => {
                alert('Failed to load purchase history.');
            });
    }



    // Function to hide the product popup
    function hideProductPopup() {

        const productPopup = document.getElementById('productPopup');
        const overlay = document.getElementById('overlay');
        if (productPopup) {
            productPopup.classList.add('hidden');
        }
        if (overlay) {
            overlay.classList.add('hidden');
        }

        console.log('hideProductPopup called');
        document.getElementById('productPopup').classList.add('hidden');
        document.getElementById('overlay').classList.add('hidden');

    }

    // Function to view cart
    function viewCart() {
        fetch(`http://127.0.0.1:8080/CustomerService/getCart?customerId=${customerId}`)
            .then(response => response.json())
            .then(cart => {
                const tbody = document.querySelector('#cartTable tbody');
                tbody.innerHTML = ''; // Clear existing rows
                cart.forEach(item => {
                    const tr = document.createElement('tr');
                    tr.innerHTML = `
                    <td>${item.productId}</td>
                    <td>${item.quantity}</td>
                    <td><button onclick="removeFromCart(${item.productId})">Remove</button></td>
                `;
                    tbody.appendChild(tr);
                });
                const cartPopup = document.getElementById('cartPopup');
                const overlay = document.getElementById('overlay');
                if (cartPopup) {
                    cartPopup.classList.remove('hidden');
                }
                if (overlay) {
                    overlay.classList.remove('hidden');
                }
            }).catch(() => {
            alert('Failed to load cart.');
        });
    }

    // Function to remove a product from the cart
    function removeFromCart(productId) {
        const customerID = String(customerId);

        fetch(`http://127.0.0.1:8080/CustomerService/removeFromCart?customerID=${encodeURIComponent(customerID)}&productId=${encodeURIComponent(productId)}`, {
            method: 'DELETE'
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('Product removed from cart.');
                    viewCart(); // Refresh the cart view
                } else {
                    alert(data.message || 'Failed to remove product from cart.');
                }
            })
            .catch(() => {
                alert('Failed to remove product from cart.');
            });
    }
    document.addEventListener('DOMContentLoaded', () => {
        const payButton = document.getElementById('payButton');

        // 封装支付功能为函数
        function initiatePayment(customerId, productId, quantity) {
            payButton.disabled = true; // 防止重复点击
            fetch('http://127.0.0.1:8080/pay', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({
                    customerId: customerId,
                    productId: productId,
                    quantity: quantity
                })
            })
                .then(response => {
                    if (response.ok) {
                        return response.text();
                    } else {
                        throw new Error('Payment failed');
                    }
                })
                .then(message => {
                    alert('Purchase successful!');
                })
                .catch(error => {
                    alert('Purchase failed: ' + error.message);
                })
                .finally(() => {
                    payButton.disabled = false; // 恢复按钮状态
                });
        }

        // 按钮点击事件
        payButton.addEventListener('click', () => {
            const customerId = 1;  // 请根据实际情况设置 customerId
            const productId = 123; // 请根据实际情况设置 productId
            const quantity = 2;    // 请根据实际情况设置 quantity
            initiatePayment(customerId, productId, quantity);
        });
    });
</script>

</body>
</html>